<template>
  <div class="app-container home">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" >
      <el-form-item label="工厂名称" prop="createBy">
        <el-select v-loadmore="factoryLoad" v-model="form.fOrgId" placeholder="请选择" @change="changeFactory">
          <el-option v-for="(item, index) in factoryList" :key="index" :label="item.fOrgName"
            :value="item.fId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称" prop="createBy">
        <el-select v-loadmore="deviceLoad" v-model="form.fDeviceId" placeholder="请选择">
          <el-option v-for="(item, index) in deviceList" :key="index" :label="item.fDeviceName"
            :value="item.fId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="tab-item" style="margin-right: 20px;">
      <el-row :gutter="20">
        <el-col :span="18">
          <strong>设备运行状态</strong>
        </el-col>
        <el-col :span="6">
          <strong>设备操作</strong>
        </el-col>
        <el-divider />
        <el-col :span="18">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" style="width: 100%">
            <el-tab-pane label="进料口" name="first">
              <el-form :label-position="labelPosition" :model="formLabelAlign">
                <el-form-item prop="configName">
                  <el-form-item label="仓位状态:">
                    <el-table-column prop="status">
                      <template slot-scope="scope">
                        <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
                      </template>
                    </el-table-column>
                  </el-form-item>
                  <el-form-item label="仓位数据(当前/上限):">
                  </el-form-item>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="温箱" name="second">
              <el-form :label-position="labelPosition" :model="formLabelAlign">
                <el-form-item prop="configName">
                  <el-form-item label="设备状态:">
                    <el-tag></el-tag>
                  </el-form-item>
                  <el-form-item label="仓位状态:">
                    <el-tag></el-tag>
                  </el-form-item>
                  <el-form-item label="使用率(当前/上限):">
                  </el-form-item>
                  <el-form-item label="网络状态:">
                    <el-tag></el-tag>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                      v-hasPermi="['system:role:add']">查看</el-button>
                  </el-form-item>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="检测工站" name="third">
              <el-form :label-position="labelPosition" :model="formLabelAlign">
                <el-form-item prop="configName">
                  <el-form-item label="设备状态:">
                    <el-tag></el-tag>
                  </el-form-item>
                  <el-form-item label="网络状态:">
                    <el-tag></el-tag>
                  </el-form-item>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="出货口" name="fourth">
              <el-form :label-position="labelPosition" :model="formLabelAlign">
                <el-form-item prop="configName">
                  <el-form-item label="当前状态:">
                    <el-tag></el-tag>
                  </el-form-item>
                  <el-form-item label="仓位状态:">
                    <el-tag></el-tag>
                  </el-form-item>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="机械臂" name="fourh">
              <el-form :label-position="labelPosition" :model="formLabelAlign">
                <el-form-item prop="configName">
                  <el-form-item label="设备状态:">
                    <el-tag></el-tag>
                  </el-form-item>
                  <el-form-item label="网络状态:">
                    <el-tag></el-tag>
                  </el-form-item>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="6">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-button type="danger">危险按钮</el-button>
            <el-button type="success">成功按钮</el-button>
          </el-tabs>
        </el-col>
        <el-col :span="6">
          <el-divider />
          <strong>报警信息</strong>
          <el-divider />
          <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
            <el-table-column label="序号" align="center" prop="fId" />
            <el-table-column label="报警位置" align="center" prop="fWarnType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.wf_warn_type" :value="scope.row.fWarnType" />
              </template>
            </el-table-column>
            <el-table-column label="严重程度" align="center" prop="fWarnStatus">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.wf_warn_status" :value="scope.row.fWarnStatus" />
              </template>
            </el-table-column>
            <el-table-column label="报警时间" align="center" prop="fWarnTime">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.fWarnTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getListe" />
        </el-col>
      </el-row>
      <el-col :span="24">
        <el-divider />
        <strong>执行工单队列</strong>
        <el-divider />
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-button>
            <div style="height: 50px;width:20%;">
              执行工单数量
            </div>
            <div>
              10
            </div>
          </el-button>
          <el-button plain>
            <div style="height: 50px; width:20%;">
              运行中工单数量
            </div>
            <div>
              10
            </div>
          </el-button>
          <el-button plain>
            <div style="height: 50px; width:20%;">
              等待中工单数量
            </div>
            <div>
              10
            </div>
          </el-button>
          <el-button plain>
            <div style="height: 50px; width:20%;">
              暂停工单数量
            </div>
            <div>
              10
            </div>
          </el-button>
          <el-button plain>
            <div style="height: 50px; width:25%;">
              即将逾期工单数量
            </div>
            <div>
              10
            </div>
          </el-button>
          <el-button plain>
            <div style="height: 50px; width:20%;">
              异常工单数量
            </div>
            <div>
              10
            </div>
          </el-button>
        </el-tabs><br>
      </el-col>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item prop="roleName">
          <el-input v-model="queryParams.roleName" placeholder="请输入关键字" clearable style="width: 240px"
            @keyup.enter.native="handleQuery" />
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-form-item><br>
        <el-form-item>
          <el-button type="danger">全部停止</el-button>
          <el-button type="success">全部执行</el-button>
          <el-button type="danger" @click="handleSuspend">批量暂停</el-button>
          <el-button type="success" @click="handleStartup">批量启动</el-button>
          <el-button type="warning" @click="handleCancel">批量取消</el-button>
          <!-- <el-col :span="1.5">
            <el-button type="danger" plain  size="mini" :disabled="multiple" >批量暂停</el-button>
          </el-col>
          <el-button type="success">批量启动</el-button>
          <el-col :span="1.5">
            <el-button type="success" plain  :disabled="multiple" >批量启动</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain  size="mini" :disabled="multiple">批量取消</el-button>
          </el-col> -->
          <el-button type="primary">优先级上移</el-button>
          <el-button type="primary">优先级下降</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column label="序号" align="center" prop="fId" />
        <el-table-column label="工单号" align="center" prop="fOrderNo" />
        <el-table-column label="工单名称" align="center" prop="fOrderName" />
        <el-table-column label="工单类型" align="center" prop="fOrderType">
          <template slot-scope="scope">
            <span>{{ scope.row.fOrderType === 0 ? '质检单' : '波形调试' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工厂名称" align="center" prop="bcmOrg.fOrgName">
        </el-table-column>
        <el-table-column label="设备名称" align="center" prop="wfDevice.fDeviceName" />
        <el-table-column label="客户" align="center" prop="bcmClient.fClientCode" />
        <el-table-column label="优先级" align="center" prop="fRunRate">
          <template slot-scope="scope">
            <span>{{
              scope.row.fOrderPriority === 0 ? '紧急' :
                scope.row.fOrderPriority === 1 ? '高' :
                  scope.row.fOrderPriority === 2 ? '中' :
                    scope.row.fOrderPriority === 3 ? '低' :
                      ''
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="执行状态" align="center" prop="fRunState">
          <template slot-scope="scope">
            <span>{{
              scope.row.fRunState === 0 ? '待运行' :
                scope.row.fRunState === 1 ? '运行中' :
                  scope.row.fRunState === 2 ? '已结束' :
                    scope.row.fRunState === 3 ? '已取消' :
                      scope.row.fRunState === 4 ? '未提交' :
                        scope.row.fRunState === 5 ? '待审核' :
                          '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="fDocumentStatus">
          <template slot-scope="scope">
            <span>{{
              scope.row.fDocumentStatus === 0 ? '保存' :
                scope.row.fDocumentStatus === 1 ? '提交' :
                  scope.row.fDocumentStatus === 2 ? '审核' :
                    scope.row.fDocumentStatus === 3 ? '重新审核' :
                      '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="执行进度" align="center" prop="fRunRate">
          <template slot-scope="scope">
            <span>{{ scope.row.fRunRate ? scope.row.fRunRate + '%' : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="fStartTime" min-width="180" />
        <el-table-column label="计时" align="center" prop="postId13" />
        <el-table-column label="预计开始时间" align="center" prop="fExpectStartTime" min-width="180" />
        <el-table-column label="最快完成时间" align="center" prop="fExpectEndTime" min-width="180" />
        <el-table-column label="最晚完成时间" align="center" prop="fLatestEndTime" min-width="180" />
        <el-table-column label="交付日期" align="center" prop="fPayDate" min-width="150" />
        <el-table-column label="是否逾期" align="center" prop="fIsOverdue">
          <template slot-scope="scope">
            <span>{{ scope.row.fIsOverdue === 0 ? '否' : '是' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="测试数量" align="center" prop="fTextNum" />
        <el-table-column label="负责人" align="center" prop="sysUser.nickName" />
        <el-table-column label="创建人" align="center" prop="fCreaterName" />
        <el-table-column label="修改人" align="center" prop="fModifierName" />
        <el-table-column label="创建时间" align="center" prop="fCreateDate" width="180">
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" min-width="300" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleCheck(scope.row)"
              v-hasPermi="['system:role:edit']">查看</el-button>
            <el-button
              v-if="(scope.row.fRunState === 0 || scope.row.fRunState === 1) && scope.row.fDocumentStatus === 2"
              size="mini" type="text" icon="el-icon-edit" @click="handleSuspend(scope.row)"
              v-hasPermi="['system:edit']">暂停</el-button>
            <el-button v-if="scope.row.fRunState === 6 && scope.row.fDocumentStatus === 2" size="mini" type="text"
              icon="el-icon-edit" @click="handleStartup(scope.row)" v-hasPermi="['system:edit']">启动</el-button>
            <el-button
              v-if="scope.row.fRunState === 1 || scope.row.fRunState === 0 || scope.row.fRunState === 5 || scope.row.fRunState === 6"
              size="mini" type="text" icon="el-icon-edit" @click="handleCancel(scope.row)"
              v-hasPermi="['system:edit']">取消</el-button> <!-- 根据状态决定是否显示 -->
            <el-button v-if="scope.row.fRunState === 4 || scope.row.fRunState === 3" size="mini" type="text"
              icon="el-icon-edit" @click="handleSubmit(scope.row)" v-hasPermi="['system:edit']">提交</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getListw" />
      <!-- 添加或修改角色配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="300px">
          <el-table v-loading="loading" :data="roleList">
            <el-table-column label="序号" prop="fId" width="120" />
            <el-table-column label="温箱编号" prop="fWarmBoxCode" width="120" align="center" />
            <el-table-column label="温箱名称" prop="fWarmBoxName" width="120" align="center" />
            <el-table-column label="温箱状态" prop="fState" width="120">
              <template slot-scope="scope">
                <dict-tag :options="scope.ro.fState" :value="scope.row.fForbidStatus" />
              </template>
            </el-table-column>
            <el-table-column label="温箱识别编号" prop="roleKey" width="120" align="center" />
            <el-table-column label="当前温度(℃)" prop="fNowNum" width="120" align="center" />
            <el-table-column label="占用情况" prop="roleKey" width="120" align="center" />
          </el-table>
        </el-form>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getLists" />
      </el-dialog>
    </div>
    <!-- 质检工单 -->
    <work-order ref="workOrder" @success="successOrder"></work-order>
    <work-order-edit ref="workOrderEdit" @success="successOrder"></work-order-edit>
    <el-dialog type="primary" :visible.sync="dialogeCi" width="60%" append-to-body>
      <el-form ref="ciObj" :model="ciObj" label-width="250" v-if="dialogeCi">
        <el-form-item label="请选择测试结束方式">
          <el-radio-group v-model="ciObj.fRetestType" @change="ciObj.fRetestNgNum = ''">
            <el-radio :label="0" style="font-size: 12px; padding: 8px 10px;">复测一次工单</el-radio><br />
            <el-radio :label="1" size="medium" style="font-size: 12px; padding: 8px 10px;">只测NG任务
              <el-select v-model="ciObj.fRetestNgNum" placeholder="请选择" :disabled="ciObj.fRetestType === 1">
                <el-option v-for="(item, index) in ciList" :key="index" :label="'第' + item + '次测试'"
                  :value="item"></el-option>
              </el-select>
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogeCi = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRole, getRole, delRole, addRole, updateRole, dataScope, changeRoleStatus, deptTreeSelect, listBox } from "@/api/system/role";
import { treeselect as menuTreeselect, roleMenuTreeselect } from "@/api/system/menu";
import { lisquality, statequality, } from "@/api/workOrder/zhidjianggd";
import { listAbn } from "@/api/abnormal/abnormalData";
import { listOrg } from "@/api/basicData/factory"
import { listDevice } from "@/api/basicData/equipment"
import workOrderEdit from "./workOrder/administration/workOrderEdit.vue";
import WorkOrder from "./workOrder/administration/workOrder.vue";
export default {
  components: {
    WorkOrder,
    workOrderEdit
  },
  name: "Role",
  dicts: ['sys_normal_disable', 'wf_warn_status', 'wf_warn_type'],
  data() {
    return {
      activeName: 'first',
      labelPosition: 'right',
      open: false,
      loading: false,
      dialogeCi: false,
      isEdit: 0,
      title: '',
      form: {
        fDeviceId: '',
      },
      rules: {},
      tableData: [],
      roleList: [],
      total: 0,
      userList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 岗位表格数据
      postList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 数据范围选项
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        },
        {
          value: "5",
          label: "仅本人数据权限"
        }
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
      },
      fForbidStatus: [
        { value: 0, label: '离线' },
        { value: 1, label: '在线' }
      ],
      fIsTackle: [
        { value: 1, label: '是' },
        { value: 0, label: '否' },

      ],
      wf_warn_status: [
        { value: 0, label: '一般' },
        { value: 1, label: '警告' },
        { value: 2, label: '非常严重' }
      ],
      wf_warn_type: [
        { value: 0, label: '机械臂' },
        { value: 1, label: '驱动板' },
        { value: 2, label: '温箱' }
      ],
      formLabelAlign: '',
      factoryWhere: { pageNum: 1, pageSize: 20 },
      deviceWhere: { pageNum: 1, pageSize: 20 },
      factoryList: [],
      deviceList: [],
    };
  },
  created() {
    this.getFactory();
    this.getList();
    this.getLists();
    this.getListw();
    this.getListe();

  },
  methods: {
    successOrder() {
      this.getLists()
    },
    handleClick(row) {
      console.log(row);
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      listRole(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
      }
      );
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then(response => {
        this.menuOptions = response.data;
      });
    },
    getLists() { },

    getListe() {
      this.loading = true;
      listAbn(this.queryParams).then(response => {
        console.log(response, 'fffffffffffff');
        if (response && response.rows) {  // 增加对响应数据的判断
          this.userList = response.rows;
          this.userList.bcmOrg = response.rows;
          this.total = response.total;
        }
        this.loading = false;
      })
        .catch(error => {
          console.error('获取列表数据时出错:', error);
        });
    },
    getListw() {
      this.loading = true;
      lisquality(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        console.log(response, 'fffffffffffff');
        if (response && response.rows) {  // 增加对响应数据的判断
          this.postList = response.rows;
          this.postList.bcmOrg = response.rows;
          this.total = response.total;
        }
        this.loading = false;
      })
        .catch(error => {
          console.error('获取列表数据时出错:', error);
        });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus;
        return response;
      });
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTree(roleId) {
      return deptTreeSelect(roleId).then(response => {
        this.deptOptions = response.depts;
        return response;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
        this.menuNodeAll = false,
        this.deptExpand = true,
        this.deptNodeAll = false,
        this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined,
          fDeviceId: '',
        };
      this.factoryWhere.pageNum = 1
      this.deviceWhere.pageNum = 1
      this.factoryList = []
      this.deviceList = []
      this.resetForm("form");
      this.getFactory()
    },
    // closeDialog() {
    //   this.factoryWhere.pageNum = 1
    //   this.deviceWhere.pageNum = 1
    //   this.factoryList = []
    //   this.deviceList = []
    // },
    changeFactory(e) {
      this.getDevices(e)
      this.form.fDeviceId = ''
    },
    getDevices(fOrgId) {
      this.deviceWhere.fOrgId = fOrgId
      listDevice(this.deviceWhere).then(res => {
        this.deviceList = res.rows
      })
    },
    getFactory() {
      listOrg(this.factoryWhere).then(res => {
        this.factoryList = [...this.factoryList, ...res.rows]
      })
    },
    getDevice() {
      listDevice(this.deviceWhere).then(res => {
        this.deviceList = [...this.deviceList, ...res.rows]
      })
    },
    factoryLoad() {
      this.factoryWhere.pageNum += 1
      this.getFactory()
    },
    deviceLoad() {
      this.deviceWhere.pageNum += 1
      this.getDevice()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true : false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true : false;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMenuTreeselect();
      this.open = true;
      this.title = "添加角色";
    },
    //暂停
    handleSuspend(row) {
      const fIds = (row.fId ? [row.fId] : this.ids)
      let data = {
        'fIds': fIds,
        'fRunState': 6 // 更新状态为暂停
      }
      statequality(data).then(response => {
        // 假设响应中包含更新后的状态信息
        this.getLists();
        this.$message.success('暂停成功');  // 显示成功消息
      }).catch(error => {
        console.error('暂停操作出错:', error);
        this.$message.error('暂停失败，请稍后重试');  // 显示失败消息
      });
    },
    //启动
    handleStartup(row) {
      const fIds = (row.fId ? [row.fId] : this.ids)
      let data = {
        'fIds': fIds,
        'fRunState': 1 // 更新状态为启动中
      }
      statequality(data).then(response => {
        this.getLists();
        this.$message.success('启动成功');
      })
        .catch(error => {
          console.error(error);
          this.$message.error('启动失败，请稍后重试');
        });
    },
    //取消
    handleCancel(row) {
      const fIds = (row.fId ? [row.fId] : this.ids)
      const data = {
        'fIds': fIds,
        'fRunState': 3, // 更新状态为已取消
      }
      console.log(data, "1111111");
      statequality(data).then(response => {
        this.getLists();
        this.$message.success('取消成功');
      })
    },
    // 查看设备操作
    handleCheck(row) {
      this.$refs.workOrderEdit.open();
      this.$refs.workOrderEdit.form = row;
      this.$refs.workOrderEdit.product = row.bcmProduct;
      this.$refs.workOrderEdit.form.check = 1;
      console.log(row, "row");
      // this.opens = true;
      // this.title = "查看工厂";
      // this.form = { ...row };
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const roleId = row.roleId || this.ids
      const roleMenu = this.getRoleMenuTreeselect(roleId);
      getRole(roleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.$nextTick(() => {
          roleMenu.then(res => {
            let checkedKeys = res.checkedKeys
            checkedKeys.forEach((v) => {
              this.$nextTick(() => {
                this.$refs.menu.setChecked(v, true, false);
              })
            })
          });
        });
        this.title = "修改角色";
      });
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== '2') {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset();
      const deptTreeSelect = this.getDeptTree(row.roleId);
      getRole(row.roleId).then(response => {
        this.form = response.data;
        this.openDataScope = true;
        this.$nextTick(() => {
          deptTreeSelect.then(res => {
            this.$refs.dept.setCheckedKeys(res.checkedKeys);
          });
        });
        this.title = "分配数据权限";
      });
    },
    /** 分配用户操作 */
    handleAuthUser: function (row) {
      const roleId = row.roleId;
      this.$router.push("/system/role-auth/user/" + roleId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.roleId != undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            updateRole(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            addRole(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function () {
      if (this.form.roleId != undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys();
        dataScope(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.openDataScope = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.roleId || this.ids;
      this.$modal.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？').then(function () {
        return delRole(roleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/role/export', {
        ...this.queryParams
      }, `role_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
